package cn.net.springboot.netty.learn.custom;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 自定义编码器
 *
 * @author Chris
 * @date 2019/05/20 16:00
 * @since 1.0.0
 */
public class LuckEncoder extends MessageToByteEncoder<LuckMessage> {
    @Override
    protected void encode(ChannelHandlerContext ctx, LuckMessage msg, ByteBuf out) throws Exception {
        // 将Message转换成二进制数据
        LuckHeader header = msg.getLuckHeader();

        // 这里写入的顺序就是协议的顺序.
        // | Version | Content-Length | SessionId | Content |

        // 写入Header信息
        out.writeInt(header.getVersion());
        out.writeInt(msg.getContent().getBytes(StandardCharsets.UTF_8).length);
        out.writeBytes(header.getSessionId().getBytes(StandardCharsets.UTF_8));

        // 写入消息主体信息
        out.writeBytes(msg.getContent().getBytes(StandardCharsets.UTF_8));
    }
}
